﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Globalization;
using C.Unite;
using C.Entities;
using ChanExt;
using MySoft.Data;
using System.Text;
using LitJson;

namespace ArtLand.OA.Project
{
    public partial class Index : CommonPageBase
    {
        #region 初始化定义
        public string scripttree = "";
        public string GetCity = "";
        public string groupflag = "";
        public string nn = "";
        public string tt = "";
        public bool ishaveqx = false;
        public string firstcityid = "";
        public string firstcityname = "";
        public string cookcity = "";
        public string ordertipcount = "";
        public string orderc = "";
        public string ChineseTimeNow = "";
        public string ForignTimeNow = "";
        public string themeValuePage = "";
        List<Sys_Modules> modelistall1 = null;
        private static ChineseLunisolarCalendar calendar = new ChineseLunisolarCalendar();
        private static string ChineseNumber = "〇一二三四五六七八九";
        public const string CelestialStem = "甲乙丙丁戊己庚辛壬癸";
        public const string TerrestrialBranch = "子丑寅卯辰巳午未申酉戌亥";
        public static readonly string[] ChineseDayName = new string[] {
            "初一","初二","初三","初四","初五","初六","初七","初八","初九","初十",
            "十一","十二","十三","十四","十五","十六","十七","十八","十九","二十",
            "廿一","廿二","廿三","廿四","廿五","廿六","廿七","廿八","廿九","三十"};
        public static readonly string[] ChineseMonthName = new string[] { "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二" };



        #region 工作流字段
        /// <summary>
        /// 未创建合同的项目
        /// </summary>
        public static int M_noconproj = 0;//未创建合同的项目
        /// <summary>
        /// 未创建订单的合同
        /// </summary>
        public static int M_noordercon = 0;//未创建订单的合同
        /// <summary>
        /// 等待审批的采购订单
        /// </summary>
        public static int M_waitauditorder = 0;//等待审批的采购订单
        /// <summary>
        /// 等待收货的订单
        /// </summary>
        public static int M_waitshou = 0;//等待收货的订单
        /// <summary>
        /// 等待送货的合同
        /// </summary>
        public static int M_waitsong = 0;//等待送货的合同
        /// <summary>
        /// 正在进行中的项目
        /// </summary>
        public static int M_nowproj = 0;//正在进行中的项目
        /// <summary>
        /// 等待审核的出样费用申请
        /// </summary>
        public static int M_waitauditamount = 0;//等待审核的出样费用申请 
        /// <summary>
        /// 等待执行的后续任务
        /// </summary>
        public static int M_wainttask = 0;//等待执行的后续任务
        /// <summary>
        /// 等待审批的行政费用申请
        /// </summary>
        public static int M_waitauditexpnse = 0;//等待审批的行政费用申请
        #endregion




        #endregion
        List<Sys_Modules> modelistall = DBCaChe.GetModelList().FindAll(delegate(Sys_Modules tbsmodel) { return tbsmodel.IsUser == true; });
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                Sys_DeskTop desk = TbsDbSession.Default.From<Sys_DeskTop>().Where(Sys_DeskTop._.Uid == CookInfo.EAdminid()).ToFirst();
                if (desk != null)
                {
                    if (desk.DeskJson.Contains("a1"))
                        chkList.Items[0].Selected = true;
                    if (desk.DeskJson.Contains("a2"))
                        chkList.Items[1].Selected = true;
                    if (desk.DeskJson.Contains("a3"))
                        chkList.Items[2].Selected = true;
                    if (desk.DeskJson.Contains("b1"))
                        chkList.Items[3].Selected = true;
                    if (desk.DeskJson.Contains("b2"))
                        chkList.Items[4].Selected = true;
                    // if (desk.DeskJson != "[]")
                    //Alert.Show(JsonMapper.ToObject(desk.DeskJson)[0].ToString());
                }

                //btnShowDesk.OnClientClick = Window4.GetShowReference();

                #region 加载修改密码事件
                ChangePwd.OnClientClick = Window2.GetShowReference("/SystemMgr/SysChangePwd.aspx", "修改密码");
                #endregion

                string week = DateTime.Now.DayOfWeek.ToString();
                switch (week)
                {
                    case "Monday":
                        week = "星期一";
                        break;
                    case "Tuesday":
                        week = "星期二";
                        break;
                    case "Wednesday":
                        week = "星期三";
                        break;
                    case "Thursday":
                        week = "星期四";
                        break;
                    case "Friday":
                        week = "星期五";
                        break;
                    case "Saturday":
                        week = "星期六";
                        break;
                    case "Sunday":
                        week = "星期日";
                        break;
                }
                TText.Text = "今天是：" + DateTime.Now.ToString("yyyy年MM月dd日") + "&nbsp;&nbsp;&nbsp;<b>" + week + "</b> （农历：" + GetChineseDate(DateTime.Now) + "）";
                string groupname = CookInfo.EAdminGroupName();
                ToolbarText1.Text = "当前登录用户：<b>" + CookInfo.EAdminTrueName() + "</b>" + "(" + CookInfo.EAdminEmpID() + ") | 所在部门：<font style='color:red;font-weight:bold;'>" + groupname + "</font> | 上次登录时间：" + CookInfo.EAdminPevTime();
                GetModels();

                #region 设定选择的样式名称
                // 设置样式和语言下拉列表的选中值
                string themeValue = PageManager1.Theme.ToString().ToLower();
                HttpCookie themeCookie = Request.Cookies["Theme"];
                if (themeCookie != null)
                {
                    themeValue = themeCookie.Value;
                }
                if (themeValue == "gray")
                {
                    M_gray.Checked = true;
                }
                if (themeValue == "blue")
                {
                    M_blue.Checked = true;
                }
                if (themeValue == "silverCherry")
                {
                    M_silverCherry.Checked = true;
                }
                //ddlTheme.SelectedValue = themeValue;
                #endregion

                MailMesSend();
                GetProjMessage();
                SetQCRecord();
            }
        }

        protected void SetQCRecord()
        {
            List<V_ProjCusTor> mainList = TbsDbSession.Default.FromSql("select * from V_ProjCusTor where isflag is null and CONVERT(varchar(100), FinshTime, 23)<=CONVERT(varchar(100), dateadd(month,-1,getdate()), 23)").ToList<V_ProjCusTor>();
            foreach (V_ProjCusTor item in mainList)
            {
                int c = TbsDbSession.Default.From<AfSale_QcInfo>().Where(AfSale_QcInfo._.ProjID == item.ID).Count();
                if (c == 0)
                {
                    AfSale_QcInfo qcInfo = new AfSale_QcInfo();
                    qcInfo.DeAttach();
                    qcInfo.QCNUBR = DFieldSN.SN(EnumData.DataSNEunm.回访记录流水号);
                    qcInfo.Adder = item.Adder;
                    qcInfo.ADDRES = item.ADDRES;
                    qcInfo.AddTime = DateTime.Now;
                    qcInfo.ATTACH = "";
                    qcInfo.CONTAT = item.CONTAT;
                    qcInfo.CUSNAM = item.CUTNAM;
                    qcInfo.CUTNUB = item.CUTNUB;
                    qcInfo.ProjID = item.ID;
                    qcInfo.PUTIME = item.FinshTime;
                    qcInfo.TELNUB = item.TELPHO;
                    qcInfo.UEMAIL = item.UEMAIL;
                    qcInfo.ProjRemark = item.DESTON;
                    TbsDbSession.Default.Insert<AfSale_QcInfo>(qcInfo);
                    TbsDbSession.Default.FromSql("update Proj_Main set isflag=1 where id=" + item.ID).ExecuteNonQuery();
                }
            }
        }


        protected void GetProjMessage()
        {
            int t = 0;
            bool f = true;
            int w = 60;
            M_noconproj = GetProjCount(0);
            M_noordercon = GetProjCount(1);
            M_waitauditorder = GetProjCount(2);
            M_waitshou = GetProjCount(3);
            M_waitsong = GetProjCount(4);
            M_nowproj = GetProjCount(5);
            M_waitauditamount = GetProjCount(6);
            M_wainttask = GetProjCount(7);
            M_waitauditexpnse = GetProjCount(9);
            int tipcount = GetProjCount(8);
            if (M_noconproj > 0)
            {
                btn1.Text = "未创建合同项目<span style=\"color:red;\">(" + M_noconproj + ")</span>";
                btn1.Hidden = false;
                f = false;
                w += 113;
                t++;
            }
            else
                btn1.Hidden = true;
            if (M_noordercon > 0)
            {
                btn2.Text = "未创建订单合同<span style=\"color:red;\">(" + M_noordercon + ")</span>";
                btn2.Hidden = false;
                f = false;
                w += 113;
                t++;
            }
            else
                btn2.Hidden = true;
            if (M_waitauditorder > 0)
            {
                btn3.Text = "未审批采购订单<span style=\"color:red;\">(" + M_waitauditorder + ")</span>";
                btn3.Hidden = false;
                f = false;
                w += 113;
                t++;
            }
            else
                btn3.Hidden = true;
            if (M_waitshou > 0)
            {
                btn4.Text = "未收货订单<span style=\"color:red;\">(" + M_waitshou + ")</span>";
                btn4.Hidden = false;
                f = false;
                w += 89;
                t++;
            }
            else
                btn4.Hidden = true;
            if (M_waitsong > 0)
            {
                btn5.Text = "未送货合同<span style=\"color:red;\">(" + M_waitsong + ")</span>";
                btn5.Hidden = false;
                f = false;
                w += 89;
                t++;
            }
            else
                btn5.Hidden = true;
            if (M_nowproj > 0)
            {
                btn6.Text = "进行中项目<span style=\"color:red;\">(" + M_nowproj + ")</span>";
                btn6.Hidden = false;
                f = false;
                w += 89;
                t++;
            }
            else
                btn6.Hidden = true;


            if (M_waitauditamount > 0)
            {

                btn7.Text = "未审批出样费用<span style=\"color:red;\">(" + M_waitauditamount + ")</span>";
                btn7.Hidden = false;
                f = false;
                w += 113;
                t++;
            }
            else
                btn7.Hidden = true;



            if (M_wainttask > 0)
            {
                btn8.Text = "后续跟单<span style=\"color:red;\">(" + M_wainttask + ")</span>";
                btn8.Hidden = false;
                f = false;
                w += 89;
            }
            else
                btn8.Hidden = true;


            if (M_waitauditexpnse > 0 && t < 8)
            {
                btn9.Text = "未审批行政费用<span style=\"color:red;\">(" + M_waitauditexpnse + ")</span>";
                btn9.Hidden = false;
                f = false;
                w += 113;
            }
            else
                btn9.Hidden = true;


            if (t > 6)
            {
                //if (M_wainttask > 0)
                //{
                //    MenuButton mb = new MenuButton();
                //    mb.Text = "后续跟单<span style=\"color:red;\">(" + M_wainttask + ")</span>";
                //    mb.OnClientClick = "top.addUTab('/Project/Pro_TaskList.aspx?s=1', 'M_wainttask', '等待执行的后续任务', '');";
                //    Button2.Menu.Items.Add(mb);
                //}
                //if (M_waitauditexpnse > 0)
                //{
                //    MenuButton mb1 = new MenuButton();
                //    mb1.Text = "未审批出样费用<span style=\"color:red;\">(" + M_waitauditamount + ")</span>";
                //    mb1.OnClientClick = "top.addUTab('/Project/Pro_SampleList.aspx?s=1', 'M_waitauditamount', '等待审批的出样费用申请', '');";
                //    Button2.Menu.Items.Add(mb1);
                //}

                if (M_waitauditamount > 0)
                {
                    MenuButton mb1 = new MenuButton();
                    mb1.Text = "未审批行政费用<span style=\"color:red;\">(" + M_waitauditexpnse + ")</span>";
                    mb1.OnClientClick = "top.addUTab('/ADM/Adm_ExpnseList.aspx?s=1', 'M_waitauditexpnse', '等待审批的行政费用申请', '');";
                    Button2.Menu.Items.Add(mb1);
                }

            }
            else
                Button2.Hidden = true;
            if (tipcount > 0)
            {
                Button4.Text = "提醒<span style=\"color:red;\">(" + tipcount + ")</span>";
                Button4.Hidden = false;
                f = false;
                w += 15;
            }
            else
                Button4.Hidden = true;

            PageContext.RegisterStartupScript("ShowDiv(" + w + ");");
            //if (f)
            //{
            //    Button5.Enabled = false;
            //}
            //else
            //    Button5.Enabled = true;
        }

        protected int GetProjCount(int mtype)
        {
            int c = 0;
            if (mtype == 0)
            {
                List<VI_C1> listinfo = TbsDbSession.Default.From<VI_C1>().Where(VI_C1._.C == 0).ToList();
                c = listinfo.Count;
            }
            if (mtype == 1)
            {
                List<VI_C2> listinfo = TbsDbSession.Default.From<VI_C2>().Where(VI_C2._.C == 0).ToList();
                c = listinfo.Count;
            }
            if (mtype == 2)
            {
                List<VI_C3> listinfo = TbsDbSession.Default.From<VI_C3>().Where(VI_C3._.C == 1).ToList();
                c = listinfo.Count;
            }
            if (mtype == 3)
            {
                List<VI_C4> listinfo = TbsDbSession.Default.From<VI_C4>().Where(VI_C4._.C == 1).ToList();
                c = listinfo.Count;
            }
            if (mtype == 4)
            {
                List<VI_C5> listinfo = TbsDbSession.Default.From<VI_C5>().Where(VI_C5._.C == 1).ToList();
                c = listinfo.Count;
            }
            if (mtype == 5)
            {
                List<VI_C6> listinfo = TbsDbSession.Default.From<VI_C6>().Where(VI_C6._.C == 1).ToList();
                c = listinfo.Count;
            }
            if (mtype == 6)
            {
                List<VI_C7> listinfo = TbsDbSession.Default.From<VI_C7>().Where(VI_C7._.C == 1).ToList();
                c = listinfo.Count;
            }
            if (mtype == 7)
            {
                List<VI_C8> listinfo = TbsDbSession.Default.From<VI_C8>().Where(VI_C8._.C == 1).ToList();
                c = listinfo.Count;
            }
            if (mtype == 8)
            {
                List<HR_MesSendLogs> logs = TbsDbSession.Default.From<HR_MesSendLogs>().Where(HR_MesSendLogs._.Uid == CookInfo.EEmpID() && HR_MesSendLogs._.IsRead == false).ToList();
                c = logs.Count;
            }
            if (mtype == 9)
            {
                List<VI_C9> listinfo = TbsDbSession.Default.From<VI_C9>().Where(VI_C9._.C > 0).ToList();
                c = listinfo.Count;
            }
            return c;
        }


        #region 样式切换
        /// <summary>
        /// 修改样式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlTheme_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedLangName = String.Empty;
            foreach (MenuItem item in btnHelp.Menu.Items)
            {
                if (item is MenuCheckBox && (item as MenuCheckBox).Checked)
                {
                    selectedLangName = item.ID;
                    break;
                }
            }

            HttpCookie themeCookie = new HttpCookie("Theme", selectedLangName.Replace("M_", ""));
            themeCookie.Expires = DateTime.Now.AddYears(1);
            Response.Cookies.Add(themeCookie);
            PageContext.Refresh();
        }
        #endregion

        #region 注册登录
        protected void LogOut(object sender, EventArgs e)
        {
            string cookname = ConfigHelper.GetWebConfigPath("LoginCookGroup");
            HttpCookie cookie = Request.Cookies[cookname];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-2);
                Response.Cookies.Set(cookie);
            }
            Response.Redirect("Login.aspx");
        }
        #endregion

        #region 取得模块
        protected void GetModels()
        {
            int i = 0;
            WhereClip wcwhere = WhereClip.All;

            modelistall1 = modelistall;
            wcwhere = wcwhere && Sys_Modules._.IsUser == true;

            List<Sys_Modules> llist = modelistall.FindAll(delegate(Sys_Modules tm) { return tm.Topmid == 0; });

            #region 未有分类用实体LIST
            List<Sys_Modules> modelist = modelistall1.FindAll(delegate(Sys_Modules tm) { return tm.Topmid == 0; });
            Accordion Accordion1 = new Accordion();
            Accordion1.ShowHeader = false;
            Accordion1.ShowBorder = false;
            Accordion1.BodyPadding = "2px";
            Accordion1.Layout = Layout.Fit;
            SetModel(modelist, Accordion1);
            Region2.Items.Remove(TabStrip1);
            Region2.Items.Add(Accordion1);
            #endregion
        }




        protected void SetModel(List<Sys_Modules> list, Accordion ad)
        {
            HttpCookie themeCookie = Request.Cookies["Theme"];
            string themeValue = "blue";
            if (themeCookie != null)
            {
                themeValue = themeCookie.Value;
            }
            int i = 0;
            foreach (Sys_Modules modelitem in list)
            {
                if (UserPower.HaveKey(modelitem.Mid, CookInfo.EAdminid(), CookInfo.EAdminGroupId(), "View"))
                {
                    scripttree += "<script>STree('RegionPanel1_Region2_Accordion1_ctl00_SysMenu_" + i + "')</script>";

                    List<Sys_Modules> childlist2 = modelistall1.FindAll(delegate(Sys_Modules tm) { return tm.Topmid == modelitem.Mid; });

                    //DataTable childlist = wcuser.protable("Sys_Modules", sqlwhere + " and topmid=" + +" ", "  order by orderid,mid desc", "mid", 1, 50);
                    //List<Sys_Modules> childlist = modellist.FindAll(delegate(Sys_Modules tmd) { return tmd.Topmid == item.Mid; });
                    Tree tr = new Tree();
                    tr.ShowHeader = false;
                    tr.ShowBorder = false;
                    tr.EnableLines = true;
                    tr.ID = "SysMenu_" + i;
                    foreach (Sys_Modules childitem in childlist2)
                    {
                        if (UserPower.HaveKey(childitem.Mid, CookInfo.EAdminid(), CookInfo.EAdminGroupId(), "View"))
                        {
                            List<Sys_Modules> treecount = modelistall1.FindAll(delegate(Sys_Modules tm) { return tm.Topmid == childitem.Mid; });

                            //DataTable treecount = wcuser.protable("Sys_Modules", sqlwhere + " and topmid=" + childlist.Rows[childitem]["mid"].ToString() + " ", "  order by orderid,mid desc", "mid", 1, 50);
                            //int treecount = modellist.FindAll(delegate(Sys_Modules tmd) { return tmd.Topmid == childitem.Mid; }).Count;
                            #region 动态添加树
                            TreeNode tn = new TreeNode();
                            tn.Text = childitem.ModeuleName;
                            tn.IconUrl = childitem.Icon;
                            if (treecount.Count == 0)
                            {
                                //tn.OnClientClick = mainTabStrip.GetAddTabReference("tab" + childitem.Mid, childitem.FunctionPage, childitem.ModeuleName, childitem.Icon, true);
                                tn.OnClientClick = "javascript:addUTab('" + childitem.FunctionPage + "','tab_" + childitem.Keyword + "','" + childitem.ModeuleName + "','" + childitem.Icon + "');";// mainTabStrip.GetAddTabReference("tab_" + childitem.Mid, childitem.FunctionPage, childitem.ModeuleName, IconHelper.GetIconUrl(Icon.Application), true);
                            }
                            // tn.NavigateUrl = childitem.FunctionPage;
                            //tn.Target = "";
                            tr.Nodes.Add(tn);
                            ResolveSubTree1(tn, treecount);
                            #endregion
                        }
                    }

                    #region 添加Plan
                    AccordionPane ap = new AccordionPane();
                    ap.AutoScroll = true;
                    ap.IconUrl = modelitem.Icon;
                    ap.Title = "<span>" + modelitem.ModeuleName + "</span>";

                    if (i == 0 && themeValue == "blue")
                    {
                        ap.CssClass = "tree_menu";
                    }
                    if (i == 0 && themeValue == "gray")
                    {
                        ap.CssClass = "tree_menu1";
                    }
                    if (i == 0 && themeValue == "first")
                    {
                        ap.CssClass = "tree_menu2";
                    }
                    if (i == 0 && themeValue == "access")
                    {
                        ap.CssClass = "tree_menu3";
                    }
                    if (i == 0 && themeValue == "second")
                    {
                        ap.CssClass = "tree_menu4";
                    }
                    if (i == 0 && themeValue == "fourth")
                    {
                        ap.CssClass = "tree_menu5";
                    }
                    if (i == 0 && themeValue == "silverCherry")
                    {
                        ap.CssClass = "tree_menu6";
                    }
                    if (i == 0 && themeValue == "cc")
                    {
                        ap.CssClass = "tree_menu2";
                    }
                    themeValuePage = themeValue;
                    ap.Items.Add(tr);

                    ad.Panes.Add(ap);

                    i++;
                    #endregion
                }
            }
        }



        private void ResolveSubTree1(TreeNode treeNode, List<Sys_Modules> dt)
        {
            if (dt.Count > 0)
            {
                treeNode.Expanded = true;
                foreach (Sys_Modules childitem in dt)
                {
                    if (UserPower.HaveKey(childitem.Mid, CookInfo.EAdminid(), CookInfo.EAdminGroupId(), "View"))
                    {
                        List<Sys_Modules> treecount = dt.FindAll(delegate(Sys_Modules tm) { return tm.Topmid == childitem.Mid; });

                        //DataTable treecount = wcuser.protable("Sys_Modules", sqlwhere + " and topmid=" + childlist.Rows[childitem]["mid"].ToString() + " ", "  order by orderid,mid desc", "mid", 1, 50);
                        //int treecount = modellist.FindAll(delegate(Sys_Modules tmd) { return tmd.Topmid == childitem.Mid; }).Count;
                        #region 动态添加树
                        TreeNode tn = new TreeNode();
                        tn.Text = childitem.ModeuleName;
                        tn.IconUrl = childitem.Icon;
                        if (treecount.Count == 0)
                        {
                            //tn.OnClientClick = mainTabStrip.GetAddTabReference("tab" + childitem.Mid, childitem.FunctionPage, childitem.ModeuleName, childitem.Icon, true);
                            tn.OnClientClick = "javascript:addUTab('" + childitem.FunctionPage + "','tab_" + childitem.Keyword + "','" + childitem.ModeuleName + "','" + childitem.Icon + "');";// mainTabStrip.GetAddTabReference("tab_" + childitem.Mid, childitem.FunctionPage, childitem.ModeuleName, IconHelper.GetIconUrl(Icon.Application), true);
                        }
                        // tn.NavigateUrl = childitem.FunctionPage;
                        //tn.Target = "";
                        treeNode.Nodes.Add(tn);
                        ResolveSubTree1(tn, treecount);
                        #endregion

                    }
                }
            }
        }
        #endregion

        #region 取得农历

        /// <summary>
        /// 获取一个公历日期对应的完整的农历日期
        /// </summary>
        /// <param name="time">一个公历日期</param>
        /// <returns>农历日期</returns>
        public string GetChineseDate(DateTime time)
        {
            string strY = GetYear(time);
            string strM = GetMonth(time);
            string strD = GetDay(time);
            //string strSB = GetStemBranch(time);
            string strDate = strM + "月 " + strD;
            return strDate;
        }
        /// <summary>
        /// 获取一个公历日期的农历干支纪年
        /// </summary>
        /// <param name="time">一个公历日期</param>
        /// <returns>农历干支纪年</returns>
        public string GetStemBranch(DateTime time)
        {
            int sexagenaryYear = calendar.GetSexagenaryYear(time);
            string stemBranch = CelestialStem.Substring(sexagenaryYear % 10 - 1, 1) + TerrestrialBranch.Substring(sexagenaryYear % 12 - 1, 1);
            return stemBranch;
        }

        /// <summary>
        /// 获取一个公历日期的农历年份
        /// </summary>
        /// <param name="time">一个公历日期</param>
        /// <returns>农历年份</returns>
        public string GetYear(DateTime time)
        {
            StringBuilder sb = new StringBuilder();
            int year = calendar.GetYear(time);
            int d;
            do
            {
                d = year % 10;
                sb.Insert(0, ChineseNumber[d]);
                year = year / 10;
            } while (year > 0);
            return sb.ToString();
        }

        /// <summary>
        /// 获取一个公历日期的农历月份
        /// </summary>
        /// <param name="time">一个公历日期</param>
        /// <returns>农历月份</returns>
        public string GetMonth(DateTime time)
        {
            int month = calendar.GetMonth(time);
            int year = calendar.GetYear(time);
            int leap = 0;

            //正月不可能闰月
            for (int i = 3; i <= month; i++)
            {
                if (calendar.IsLeapMonth(year, i))
                {
                    leap = i;
                    break; //一年中最多有一个闰月
                }

            }
            if (leap > 0) month--;
            return (leap == month + 1 ? "闰" : "") + ChineseMonthName[month - 1];
        }


        /// <summary>
        /// 获取一个公历日期的农历日
        /// </summary>
        /// <param name="time">一个公历日期</param>
        /// <returns>农历日</returns>
        public string GetDay(DateTime time)
        {
            return ChineseDayName[calendar.GetDayOfMonth(time) - 1];
        }
        #endregion

        protected void btnDeskSave_Click(object sender, EventArgs e)
        {
            string[] arr = chkList.SelectedValueArray;
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            for (int i = 0; i < arr.Length; i++)
            {
                List<string> ls = StringHelper.GetSubStringList(arr[i], ';');
                sb.Append("{\"id\":\"" + ls[0] + "\",\"col\":" + ls[1] + ",\"row\":" + ls[2] + "},");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("]");
            Sys_DeskTop deskTop = new Sys_DeskTop();
            Sys_DeskTop desk = TbsDbSession.Default.From<Sys_DeskTop>().Where(Sys_DeskTop._.Uid == CookInfo.EAdminid()).ToFirst();
            if (desk != null)
            {
                deskTop.ID = desk.ID;
                deskTop.Attach();
                deskTop.DeskJson = sb.ToString();
                TbsDbSession.Default.Update<Sys_DeskTop>(deskTop);
            }
            else
            {
                deskTop.DeAttach();
                deskTop.Uid = CookInfo.EAdminid();
                deskTop.DeskJson = sb.ToString();
                TbsDbSession.Default.Insert<Sys_DeskTop>(deskTop);
            }
            //Tab2.IFrameUrl = "/Main.aspx";
            PageContext.RegisterStartupScript(Window4.GetHideReference() + "top.x31_iframe.location.href='Main.aspx';");
        }

        protected void hid_btn_Click(object sender, EventArgs e)
        {
            //  Alert.Show("1");
            GetProjMessage();
        }

        protected void btn1_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript("top.addUTab('/Project/Pro_MainList.aspx?t=1', 'noproj_x', '未创建合同项目', '');");
            //  FormInfo.ShowTab("/Project/Pro_MainList.aspx?t=1", "noproj", "", "未创建合同的项目");
        }

        protected void time1_Tick(object sender, EventArgs e)
        {
            GetProjMessage();

        }

        protected void btn2_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript("top.addUTab('/Project/Pro_ContatList.aspx?t=1', 'M_noordercon_x', '未创建订单合同', '');");
        }

        protected void btn3_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript("top.addUTab('/Project/Pro_PoDataList.aspx?t=1', 'M_waitauditorder_x', '未审批采购订单', '');");
        }

        protected void btn4_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript("top.addUTab('/Project/Pro_PoDataList.aspx?m=1', 'M_waitshou_x', '未收货订单', '');");
        }

        protected void btn5_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript("top.addUTab('/Project/Pro_ContatList.aspx?s=1', 'M_waitsong_x', '未送货合同', '');");
        }

        protected void btn6_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript("top.addUTab('/Project/Pro_MainList.aspx?s=1', 'M_nowproj', '进行中项目', '');");
        }

        protected void btn7_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript("top.addUTab('/Project/Pro_SampleList.aspx?s=1', 'M_waitauditamount', '未审批出样费用', '');");
        }

        protected void btn8_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript("top.addUTab('/Project/Pro_TaskList.aspx?s=1', 'M_wainttask', '后续跟单', '');");
        }


        protected void btn9_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript("top.addUTab('/ADM/Adm_ExpnseList.aspx?s=1', 'M_waitauditexpnse', '未审批行政费用', '');");
        }

        protected static string dirhrmailbody = @"亲爱的{0}，<br>  {1}再有{2}就需要转正了，请提醒其直线主管批准她/他的转正。";
        protected static string dirmailbody = @"亲爱的{0}，<br>  {1}再有{2}就需要转正了，请您及时批准。";

        protected static string birthdaybody7 = "再过7天是{1}的生日，记得给他/她惊喜。谢谢！";
        protected static string birthdaybody1 = "今天是{1}的生日，感谢您为公司的付出，祝你生日快乐。谢谢！";


        protected void MailMesSend()
        {
            int mtype = 0;
            #region 员工转正提醒
            List<HR_CONTRACT> con = TbsDbSession.Default.From<HR_CONTRACT>().Where(HR_CONTRACT._.CEKSAT != 2 && HR_CONTRACT._.PositiveTime.Between(DateTime.Now.AddDays(-1), DateTime.Now.AddDays(7))).ToList();

            WhereClip wc = WhereClip.All;
            wc = wc && HR_CONTRACT._.PositiveTime > DateTime.Now.AddDays(-1).ToString() && HR_CONTRACT._.PositiveTime < DateTime.Now.AddDays(1).ToString();

            List<HR_CONTRACT> con1 = TbsDbSession.Default.From<HR_CONTRACT>().Where(HR_CONTRACT._.CEKSAT != 2 && wc).ToList();

            foreach (HR_CONTRACT item in con)
            {
                mtype = 0;
                int cc = TbsDbSession.Default.From<HR_MailSendLogs>().Where(HR_MailSendLogs._.Sid == item.ID && HR_MailSendLogs._.Mtype == mtype).Count();
                if (cc == 0)
                {
                    string d = DateTimeDiff.DateDiff(item.PositiveTime.Value);
                    HR_EMP empuser = TbsDbSession.Default.From<HR_EMP>().Where(HR_EMP._.EMPLID == item.EMPLID).ToFirst();
                    HR_EMP emp = TbsDbSession.Default.From<HR_EMP>().Where(HR_EMP._.EMPLID == item.DIRMGR).ToFirst();
                    if (emp != null)
                    {
                        string body = string.Format(dirmailbody, emp.EMNAME, empuser.EMNAME, d);
                        SetMail("转正提醒", body, emp, mtype, item.ID, empuser.EMNAME, d, true);
                    }

                    HR_EMP hremp = TbsDbSession.Default.From<HR_EMP>().Where(HR_EMP._.EMPLID == item.HRMMGR).ToFirst();
                    if (hremp != null)
                    {
                        string body = string.Format(dirmailbody, emp.EMNAME, empuser.EMNAME, d);
                        SetMail("转正提醒", body, hremp, mtype, item.ID, empuser.EMNAME, d, true);
                    }
                }
            }

            foreach (HR_CONTRACT item in con1)
            {
                mtype = 1;
                int cc = TbsDbSession.Default.From<HR_MailSendLogs>().Where(HR_MailSendLogs._.Sid == item.ID && HR_MailSendLogs._.Mtype == mtype).Count();
                if (cc == 0)
                {
                    string d = DateTimeDiff.DateDiff(item.PositiveTime.Value);
                    HR_EMP empuser = TbsDbSession.Default.From<HR_EMP>().Where(HR_EMP._.EMPLID == item.EMPLID).ToFirst();
                    HR_EMP emp = TbsDbSession.Default.From<HR_EMP>().Where(HR_EMP._.EMPLID == item.DIRMGR).ToFirst();
                    if (emp != null)
                    {
                        string body = string.Format(dirmailbody, emp.EMNAME, empuser.EMNAME, d);
                        SetMail("转正提醒", body, emp, mtype, item.ID, empuser.EMNAME, d, true);
                    }

                    HR_EMP hremp = TbsDbSession.Default.From<HR_EMP>().Where(HR_EMP._.EMPLID == item.HRMMGR).ToFirst();
                    if (hremp != null)
                    {
                        string body = string.Format(dirhrmailbody, hremp.EMNAME, empuser.EMNAME, d);
                        SetMail("转正提醒", dirhrmailbody, hremp, mtype, item.ID, empuser.EMNAME, d, true);
                    }
                }
            }


            #endregion

            #region 生日提醒
            List<HR_EMP> hem = TbsDbSession.Default.FromSql("select * from HR_EMP where substring(convert(varchar(10), birdat,110),1,5)='" + DateTime.Now.AddDays(7).ToString("MM-dd") + "'").ToList<HR_EMP>();//.From<HR_EMP>().Where(HR_EMP._.BIRDAT.Month == DateTime.Now.Month && HR_EMP._.BIRDAT.Day == 7).ToList();
            wc = WhereClip.All;
            wc = wc && HR_EMP._.BIRDAT.Month == DateTime.Now.Month && HR_EMP._.BIRDAT.Day == DateTime.Now.Day;

            List<HR_EMP> hem1 = TbsDbSession.Default.From<HR_EMP>().Where(wc).ToList();
            foreach (HR_EMP item in hem)
            {
                string d = DateTimeDiff.DateDiff(item.BIRDAT.Value);
                mtype = 2;
                HR_CONTRACT contract = TbsDbSession.Default.From<HR_CONTRACT>().Where(HR_CONTRACT._.EMPLID == item.EMPLID).ToFirst();
                if (contract != null)
                {
                    int cc = TbsDbSession.Default.From<HR_MailSendLogs>().Where(HR_MailSendLogs._.Sid == contract.ID && HR_MailSendLogs._.Mtype == mtype).Count();
                    if (cc == 0)
                    {
                        HR_EMP hremp = TbsDbSession.Default.From<HR_EMP>().Where(HR_EMP._.EMPLID == contract.HRMMGR).ToFirst();
                        if (hremp != null)
                        {
                            string body = string.Format(birthdaybody7, hremp.EMNAME, item.EMNAME, d);
                            SetMail("生日提醒", body, hremp, mtype, item.ID, item.EMNAME, d, true);
                        }
                    }
                }
            }

            foreach (HR_EMP item in hem1)
            {
                string d = DateTimeDiff.DateDiff(item.BIRDAT.Value);
                mtype = 3;
                HR_CONTRACT contract = TbsDbSession.Default.From<HR_CONTRACT>().Where(HR_CONTRACT._.EMPLID == item.EMPLID).ToFirst();
                if (contract != null)
                {
                    int cc = TbsDbSession.Default.From<HR_MailSendLogs>().Where(HR_MailSendLogs._.Sid == contract.ID && HR_MailSendLogs._.Mtype == mtype).Count();
                    if (cc == 0)
                    {
                        HR_EMP hremp = TbsDbSession.Default.From<HR_EMP>().Where(HR_EMP._.EMPLID == contract.HRMMGR).ToFirst();
                        if (hremp != null)
                        {
                            string body = string.Format(birthdaybody1, hremp.EMNAME, item.EMNAME, d);
                            SetMail("生日提醒", body, hremp, mtype, item.ID, item.EMNAME, d, true);
                        }
                    }
                }
            }
            #endregion


        }

        protected void SetMail(string mailtitle, string sendmailbody, HR_EMP emp, int mtype, int senduid, string sendname, string days, bool ismes)
        {
            int send = TbsDbSession.Default.From<HR_MailSendLogs>().Where(HR_MailSendLogs._.AuditUid == emp.ID && HR_MailSendLogs._.Sid == senduid && HR_MailSendLogs._.Mtype == mtype).Count();
            if (send == 0)
            {
                
                HR_MailSendLogs mail = new HR_MailSendLogs();
                mail.DeAttach();
                mail.Mail = emp.UEMAIL;
                mail.Mtype = mtype;
                mail.SendTime = DateTime.Now;
                mail.Sid = senduid;
                mail.AuditUid = emp.ID;
                TbsDbSession.Default.Insert<HR_MailSendLogs>(mail);
                string mailbody = sendmailbody;//
                ToolHelper.sendMail(emp.UEMAIL, mailbody, mailtitle);
                if (ismes)
                {
                    HR_MesSendLogs mes = new HR_MesSendLogs();
                    mes.DeAttach();
                    mes.Message = mailbody;
                    mes.Title = mailtitle;
                    mes.Uid = emp.ID;
                    mes.Sid = senduid;
                    mes.Mtype = mtype;
                    mes.SendTime = DateTime.Now;
                    mes.IsRead = false;
                    mes.FUrl = "/HR/HR_ContractList.aspx?cid=" + senduid;
                    TbsDbSession.Default.Insert<HR_MesSendLogs>(mes);
                }
            }
        }


        protected void Button4_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript("top.addUTab('/SystemMgr/SysMessage.aspx', 'M_message', '任务提醒', '');");
        }

        protected void Timer2_Tick(object sender, EventArgs e)
        {
            MailMesSend();
        }



    }
}